package com.tbit.uqbike.webmanager.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.tbit.common.enums.OperaPswEnum;
import com.tbit.common.utils.TraceUtil;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.AccountUser;
import com.tbit.uqbike.object.pojo.FeeAppeal;
import com.tbit.uqbike.object.pojo.MachineRideLog;
import com.tbit.uqbike.object.pojo.vo.FeeAppealInfoVO;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.business.OperaPswService;
import com.tbit.uqbike.service.business.OrderFeeAppealService;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.MD5PasswordUtil;
import com.tbit.uqbike.webmanager.util.ServletUtils;
import com.tbit.uqbike.webmanager.util.csv.config.CsvExportConfig;
import com.tbit.uqbike.webmanager.util.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单费用申诉
 *
 * @Author HZW
 * @ClassName OrderFeeAppeal
 * @Description 订单费用申诉Controller层
 * @date 2021/12/20 11:20
 * @Version 1.0
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/orderAppeal")
public class OrderFeeAppealController extends BaseController {
    @Resource
    private OrderFeeAppealService orderFeeAppealService;
    @Autowired
    CsvExportConfig config;
    @Autowired
    private OperaPswService operaPswService;

    /**
     * @描述 查询订单费用申诉的详情
     * @参数
     * @创建人 hzw
     * @创建时间 2021/12/20
     * @修改人和其它信息
     */
    @RequestMapping("/queryPage")
    public JsonResult queryPage(FeeAppeal feeAppeal) {
        startPage();
        List<FeeAppeal> list = orderFeeAppealService.getInfo(feeAppeal);
        return JsonResult.ok(list, (int) new PageInfo<>(list).getTotal());
    }

    @GetMapping("/orderInfo/{orderNo}")
    public Result<MachineRideLog> queryOrderInfoByOrderNo(@PathVariable String orderNo) {
        return orderFeeAppealService.queryOrderInfoByOrderNo(orderNo);
    }

    /**
     * @描述 导出订单费用申诉
     * @参数
     * @创建人 hzw
     * @创建时间 2021/12/20
     * @修改人和其它信息
     */
    @PostMapping("/excel")
    public Result excel(FeeAppeal feeAppeal) {
        int count = orderFeeAppealService.getBigExcelCount(feeAppeal);
        if (count <= config.getBigDataQueryCount()) {//小数据量
            List<FeeAppeal> list = orderFeeAppealService.getInfo(feeAppeal);
            for (FeeAppeal appeal : list) {
                appeal.setMoney(appeal.getMoney() / 100);
            }
            ExcelUtil<FeeAppeal> excelUtil = new ExcelUtil<>(FeeAppeal.class);
            JsonResult result = excelUtil.exportExcel(list, "订单费用申诉列表");
            return Result.success(result.getData());
        }
        else {//大数据量
            log.info("大数据量下载");
            feeAppeal.setCount(count);
            Result result = orderFeeAppealService.bigExcelInfo(feeAppeal);
//            result.setMsg("正在导出，可以在下载历史中查看导出结果。");
//            result.setCode(HttpStatus.SUCCESS);
            return result;
        }
    }


    /**
     * @描述 导出订单费用申诉, 使用easyExcel，目前不使用这个接口
     * @参数
     * @创建人 hzw
     * @创建时间 2021/12/20
     * @修改人和其它信息
     */
    @RequestMapping("/easyExcel")
    public JsonResult easyExcel(FeeAppeal feeAppeal, HttpServletResponse resp) {
        List<FeeAppeal> list = orderFeeAppealService.getInfo(feeAppeal);
        try {
            ExcelUtil.writeExcel(resp, list, "订单费用申诉", "sheet", FeeAppeal.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            JsonResult.fail("导出失败，请联系管理员", TraceUtil.getTraceIdByLocal());
        }
        return JsonResult.ok("导出成功");
    }

    /**
     * @描述 处理回复
     * @参数
     * @创建人 hzw
     * @创建时间 2021/12/20
     * @修改人和其它信息
     */
    @RequestMapping("/result")
    public JsonResult result(@Valid FeeAppeal feeAppeal) throws ParseException {
        LoginInfo login = getLogin(ServletUtils.getRequest());
        /**操作密码校验*/
        operaPswService.checkOperaPsw(login, OperaPswEnum.OPERA_PSW_ORDER_CONFIG.getModule(), feeAppeal.getOperaPsw());

        /**申诉驳回*/
        if (!feeAppeal.getState().equals(1)) {
            Assert.notNull(feeAppeal.getCompensationId(), "ver.compensationId.notNull");
        }

        Boolean flag = orderFeeAppealService.handle(feeAppeal, login);
        return flag ? JsonResult.ok() : JsonResult.fail("请联系管理员",TraceUtil.getTraceIdByLocal());
    }


    /**
     * 提供给运维端远程处理工单
     *
     * @param map accountIds 区域id集合 startDt 开始时间 endDt 结束时间
     * @return result
     */
    @RequestMapping("/getresult")
    public Map<String, Object> getresult(@RequestBody Map<String, Object> map)  {
        HashMap<String, Object> stringBooleanHashMap = new HashMap<>();
        boolean result = MD5PasswordUtil.signCheck(map.get("sign").toString(), Long.parseLong(map.get("date").toString()), map.get("param").toString());
        if (!result) {
            throw new BaseException("签名校验失败");
        }
        FeeAppeal feeAppeal = JSONObject.parseObject(map.get("feeAppeal").toString(), FeeAppeal.class);
        AccountUser accountUser = JSONObject.parseObject(map.get("accountUser").toString(), AccountUser.class);

        /**申诉驳回*/
        if (!feeAppeal.getState().equals(1)) {
            if (feeAppeal.getCompensationId() == null){
                stringBooleanHashMap.put("data",0);
                stringBooleanHashMap.put("text","处理方式不能为空");
                return stringBooleanHashMap;
            }
        }
        LoginInfo login = new LoginInfo();
        login.setName(accountUser.getName());
        login.setPhone(accountUser.getPhone());
        login.setAccountUserId(accountUser.getAccountUserId());
        Boolean handle = null;
        try {
            handle = orderFeeAppealService.handle(feeAppeal, login);
            stringBooleanHashMap.put("data",handle);
        }catch (BaseException e) {
            stringBooleanHashMap.put("data",0);
            stringBooleanHashMap.put("text",e.getMsgId());
        } catch (Exception e) {
            stringBooleanHashMap.put("data",0);
            stringBooleanHashMap.put("text",e.getMessage());
        }
        return stringBooleanHashMap;
    }

    /**
     * 根据用户id获取用户申诉统计
     *
     * @param userId 用户id
     */
    @GetMapping("/getAppealStats")
    public Result<FeeAppealInfoVO> getAppealStats(@NotNull Integer userId){
        return Result.success(orderFeeAppealService.getAppealStats(userId));
    }

}
